package concept.misc;

import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

public class SpecialCharLab
{
	private static String encoding;
	
	public static void main(String[] args) throws IOException
	{
		System.out.printf("%1$s %2$s \n%3$s %4$s\n", "input: ", args[0], "output: ", args[1]);
		if(args.length < 3)
		{
			System.err.println(String.format("Arguments: [%s] [%s] [%s]", "inputFileName", "outputFileName", "Encoding standard"));
			System.exit(-1);
		}
		String inputFile = args[0];
		String outputFile = args[1];
		encoding = args[2];
		
		InputStream is = new FileInputStream(inputFile);
		
		InputStreamReader sr = new InputStreamReader(is);

		StringBuilder sb = read(sr);
		
		//print(sb);
		
		save(sb, outputFile);
		
		//char c = '\t';
		
		//System.out.println("char: >"+c+"<");
		
		/*for(int c=0x0; c<0xF; c++)
		{
			getCharType(c);
		}*/
		
		
	}
	
	private static void getCharType(int ch)
	{
		System.out.println(ch+" is of type: "+Character.getType(ch));
	}
	
	private static StringBuilder read(Reader reader) throws IOException
	{
		StringBuilder sb = new StringBuilder();
		if(reader instanceof InputStreamReader)
		{
			out.println(String.format("Input encoding: %s", ((InputStreamReader)reader).getEncoding()));
		}
		int c;
		
		BufferedReader br = new BufferedReader(reader);
		
		String line;
		
		while((line=br.readLine())!=null)
		{
			sb.append(line);
		}
		
		/*while((c=reader.read())!=-1)
		{
			sb.append((char)c);
		}*/
		
		reader.close();
		br.close();
		return sb;
	}
	
	private static void save(StringBuilder sb, String filename) throws IOException
	{
		OutputStream os = new FileOutputStream(filename);
//		OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
		OutputStreamWriter osw = new OutputStreamWriter(os);
		
		out.println(String.format("Output encoding: %s",osw.getEncoding()));
		
		osw.write(sb.toString());
		
		osw.flush();
		osw.close();
		
		/*PrintStream out = new PrintStream(os, true, encoding);
		
		out.write(sb.toString().getBytes(encoding));
		out.close();*/
	}
	
	private static void print(StringBuilder sb) throws UnsupportedEncodingException
	{
		//OutputStream os = new ByteArrayOutputStream();
		
		OutputStream os = System.out;
		
		PrintStream out = new PrintStream(os, true);
		
		out.println(sb);
		out.close();
	}
}
